package collectors

import (
	"net/http"
	"strconv"

	"github.com/asxjd/domainexpiry/common"
	"github.com/prometheus/client_golang/prometheus"
	"github.com/prometheus/client_golang/prometheus/promhttp"
)

var (
	DomainExporterCollector *DomainCollector
)

func init() {
	DomainExporterCollector = newDomainCollector("domain_expire_info", "dns域名过期时间,单位小时")
}

type DomainCollector struct {
	dnsExpiryDesc *prometheus.Desc
}

func newDomainCollector(name string, help string) *DomainCollector {
	l_ := make([]string, 0, 4)
	l_ = append(l_, "name", "create", "update", "expire")
	return &DomainCollector{
		dnsExpiryDesc: prometheus.NewDesc(
			name, help, l_, prometheus.Labels{},
		)}
}

func (d *DomainCollector) Describe(ch chan<- *prometheus.Desc) {
	ch <- d.dnsExpiryDesc
}

func (d *DomainCollector) Collect(ch chan<- prometheus.Metric) {
	entrys := common.MultiParse(common.NameParse())
	for _, whos := range entrys {
		f, _ := strconv.ParseFloat(whos[3], 64)
		labels := make([]string, 0, 3)
		labels = append(labels, whos[4], whos[0], whos[1], whos[2])
		ch <- prometheus.MustNewConstMetric(d.dnsExpiryDesc, prometheus.GaugeValue, f, labels...)
	}
}

func Srv() error {
	registry := prometheus.NewRegistry()
	registry.MustRegister(DomainExporterCollector)

	http.Handle(
		"/metrics", promhttp.HandlerFor(registry, promhttp.HandlerOpts{Registry: registry}),
	)
	err := http.ListenAndServe(":"+common.Port, nil)
	return err
}
